/*
 * Client.cpp
 *
 *  Created on: 2009-12-21
 *      Author: Maciej Skrzypkowski
 */

#include "Client.h"

Client::Client() {
	char line[256];
	serversNum = 0;
	filebuf fb;

	// wyczytanie listy serwerów z pliu konfiguracyjnego
	fb.open (CONF_FILE, ios::in);
	istream is(&fb);
	while (!is.eof()) {
		is.getline(line, 256);
		servers[serversNum] = line;
		++serversNum;
		if (serversNum == SERVERS_NUM) {
			Log::instance()->error("Za duzo serwerow zdefiniowanych w pliku konfiguracyjnym!");
			exit(0);
		}
	}
	fb.close();
}

Client::~Client() {
}

void Client::_run()
{
	Log::instance()->info("klient startuje");

	char line[256];
	int i=0;

	cout<<"Lista serwerow: \n";
	while (i < serversNum) {
		cout<<i<<": "<<servers[i]<<"\n";
		++i;
	}

	do {
		cout<<"Polecenie: <numer_serwera> <operacja> <nazwa_semafora> \n";
		cout<<"Operacje: c - connect, d - disconnect, n - create semaphore, t - delete semaphore, "
				"p - p semaphore, v -v semaphore, e - exit \n";
		cout<<">> ";

		memset(line, 0, sizeof(line));

		if (cin.getline(line, 256) <= 0)
			continue;

		i = atoi((const char*)&line[0]);
		char semafor[32];
		strcpy(semafor, (const char*)&line[4]);

		switch (line[2]) {
		case 'c':
			SemLib::instance()->connect(servers[i].c_str());
			break;
		case 'd':
			SemLib::instance()->disconnect(servers[i].c_str());
			break;
		case 'n':
			SemLib::instance()->createSemaphore(semafor, servers[i].c_str());
			break;
		case 't':
			SemLib::instance()->deleteSemaphore(semafor, servers[i].c_str());
			break;
		case 'p':
			SemLib::instance()->pSemaphore(semafor, servers[i].c_str());
			break;
		case 'v':
			SemLib::instance()->vSemaphore(semafor, servers[i].c_str());
			break;
		}
	} while (line[2] != 'e' && line[0] != 'e');

	Log::instance()->info("klient zakonczyl");
}


